
var gamejs = require('gamejs');
var matrix;
var handleEvent = function(event) {
   if (event.type === gamejs.event.WORKER) {
	   if (event.data.todo === 'find') {    
			var graph = new Graph(matrix);
			var start = graph.nodes[Math.floor(event.data.wstartPoint[0])][Math.floor(event.data.wstartPoint[1])];
			var end = 	graph.nodes[Math.floor(event.data.wendPoint[0])][Math.floor(event.data.wendPoint[1])];
			var result = astar.search(graph.nodes, start, end);
			var path = [];
			for(var i = 0; i< result.length; i++){
				path[i] =  [];
			    path[i][0] = result[i].x;
			    path[i][1] = result[i].y;
			}
		    gamejs.event.post({type: gamejs.event.WORKER_RESULT,data: {wid : event.data.wid,wpath: path}});   
   		}
	   if (event.data.todo === 'map') {    
			matrix = event.data.wmatrix;
  		}
	}
}
gamejs.ready(function() {
   var handletick = function(msDuration) {
      gamejs.event.get().forEach(handleEvent);
   }
   gamejs.time.fpsCallback(handletick, null, 1000);
})